//
//  HBView.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/9/1.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "HBView.h"
#import "RedShowView.h"
#import "HoongBaoItemTableViewCell.h"
#import "MYHBViewController.h"

@interface HBView ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) NSTimer *hbTimer;

@property (nonatomic, strong) NSTimer *hbListTimer;

@property (nonatomic, strong) CALayer *moveLayer;

@property (strong, nonatomic) UITableView *redTable;

@property (nonatomic, strong) NSMutableArray *hArray;

@property (nonatomic, strong) NSDictionary *dateSelfDic;

@property (nonatomic, assign) NSInteger selTimeIndex;

@property (nonatomic, assign) CGFloat tableHeightWith;

@property (nonatomic, strong) NSArray *dataArray;

@property (nonatomic, strong) UIButton *voiceButton;


@end

@implementation HBView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void)awakeFromNib{
    [super awakeFromNib];
    self.redTable = [[UITableView alloc]initWithFrame:CGRectMake(0, self.gongImage.frame.origin.y + 15, ScreenWidth, self.gongImage.frame.size.height)];
    [self.redTable setDataSource:self];
    [self.redTable setDelegate:self];
    [self.redTable setUserInteractionEnabled:NO];
    [self.redTable setBackgroundColor:[UIColor clearColor]];
    [self.redTable setSeparatorColor:[UIColor clearColor]];
    [self.redTable registerNib:[UINib nibWithNibName:@"HoongBaoItemTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"Cell"];
    [self insertSubview:self.redTable belowSubview:self.hbBgView];
    
    self.voiceButton = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth - 31, ScreenHeight - 250, 31, 31)];
    [self.voiceButton setSelected:[[[NSUserDefaults standardUserDefaults] objectForKey:@"hbVoice"] boolValue]];
    [self.voiceButton setImage:[UIImage imageNamed:@"music-voice"] forState:UIControlStateNormal];
    [self.voiceButton setImage:[UIImage imageNamed:@"矩形-7-voice"] forState:UIControlStateSelected];
    [self.voiceButton addTarget:self action:@selector(voiceEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.voiceButton];
    
    UITapGestureRecognizer *clickgest = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickEvent:)];
    [self.hbBgView addGestureRecognizer:clickgest];
    
}

- (void)voiceEvent:(UIButton *)sender{
    if (sender.selected == YES) {
        sender.selected = NO;
    }else{
        sender.selected = YES;
    }
    [[NSUserDefaults standardUserDefaults] setValue:@(sender.selected) forKey:@"hbVoice"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self.delegate changeVoice:sender.selected];
    
}

- (void)loadDataAni{
    if (self.hArray.count > 7) {
        [self.hbListTimer invalidate];
        self.hbListTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(srcollTable) userInfo:nil repeats:YES];
    }
}

- (void)srcollTable{
    if ((self.redTable.contentSize.height - self.redTable.frame.size.height) - self.redTable.contentOffset.y < 10) {
        [self.hArray addObjectsFromArray:self.dataArray];
        [self.redTable reloadData];
    }
    self.tableHeightWith = self.tableHeightWith + 0.5;
    [self.redTable setContentOffset:CGPointMake(0, self.tableHeightWith)];
}

- (void)loadHongBaoUserData:(NSDictionary *)dataDic selindex:(NSInteger)index{
    self.dateSelfDic = dataDic;
    [self.tipsLabel setText:[dataDic objectForKey:@"configtext"]];
    NSArray *timeArray = [dataDic objectForKey:@"time"];
    if (timeArray && [timeArray isKindOfClass:[NSArray class]]) {
        NSMutableArray *showTime = [[NSMutableArray alloc]init];
        for (NSDictionary *timeItem in timeArray) {
            NSString *timeString = [timeItem objectForKey:@"time"];
            if (timeString.length == 8) {
                NSString *newtimeString = [timeString substringToIndex:[timeString length] - 3];
                [showTime addObject:newtimeString];
            }else{
                 [showTime addObject:timeString];
            }
            
        }
        self.jiduView = [[XFStepView alloc]initWithFrame:CGRectMake(0, 470, ScreenWidth, 80) Titles:showTime];
        [self insertSubview:self.jiduView belowSubview:self.hbBgView];
        
        [self timeCompare:showTime];
        
    }
    
    [self loadData];
    NSDictionary *selTimeDic = [timeArray objectAtIndex:index];
    if ([[selTimeDic objectForKey:@"isget"] integerValue] == 3) {
        [self start];
    }
}

- (void)loadHongBaoUserTiQianData:(NSDictionary *)dataDic Tiqian:(NSInteger)tq{
    self.dateSelfDic = dataDic;
    [self.tipsLabel setText:[dataDic objectForKey:@"configtext"]];
    NSArray *timeArray = [dataDic objectForKey:@"time"];
    if (timeArray && [timeArray isKindOfClass:[NSArray class]]) {
        NSMutableArray *showTime = [[NSMutableArray alloc]init];
        for (NSDictionary *timeItem in timeArray) {
            NSString *timeString = [timeItem objectForKey:@"time"];
            if (timeString.length == 8) {
                NSString *newtimeString = [timeString substringToIndex:[timeString length] - 3];
                [showTime addObject:newtimeString];
            }else{
                [showTime addObject:timeString];
            }
            
        }
        self.jiduView = [[XFStepView alloc]initWithFrame:CGRectMake(0, 450, ScreenWidth, 80) Titles:showTime];
        [self insertSubview:self.jiduView belowSubview:self.hbBgView];
        
        [self timeCompare:showTime];
        
    }
    
    [self loadData];
    float moth = tq * 60.0;
    [self performSelector:@selector(start) withObject:nil afterDelay:moth];
}


- (void)timeCompare:(NSArray *)timeA{
    NSString *nTime = [self getyNowTimeDayHour];
    nTime = [nTime substringToIndex:[nTime length] - 1];
    int sel = 0;
    
    for (int i = 0; i < timeA.count; i ++) {
        NSString *t = [timeA objectAtIndex:i];
        NSArray *tt = [t componentsSeparatedByString:@":"];
        NSInteger ntimeInt = [nTime integerValue];
        NSInteger btt = [[tt firstObject] integerValue];
        if (ntimeInt > btt) {
            sel = i;
            self.selTimeIndex = i;
        }
    }
    [self.jiduView setStepIndex:sel];
}


- (NSString *)getyNowTimeDayHour{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"hh"];
    NSString *DateTime = [formatter stringFromDate:date];
    return DateTime;
}

- (void)loadData{
    NSString *str = [NSString stringWithFormat:@"%@890d69e502d1d37a9e84335ccefece57",[user objectForKey:@"token2"]];
    NSString *token = [LCMD5Tool md5:str];
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setValue:token forKey:@"verifyToken"];
    [parmas setValue:[user objectForKey:@"userid"] forKey:@"id"];
    
    NSString *url = [NSString stringWithFormat:@"%@/App/Voucher/getRedList",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSInteger error = [[responseObject objectForKey:@"error"] integerValue];
        self.dataArray = [responseObject objectForKey:@"result"];
        if (error == 200 && [self.dataArray isKindOfClass:[NSArray class]]) {
            self.hArray = [self.dataArray mutableCopy];
            [self.redTable reloadData];
            [self loadDataAni];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    
}


- (void)clickEvent:(UITapGestureRecognizer *)gest{
    CGPoint touchPoint = [gest locationInView:self.hbBgView];
    NSArray *sublayers = self.hbBgView.layer.sublayers;
    for (int i = 0; i < sublayers.count; i ++) {
        CALayer *lay = [sublayers objectAtIndex:i];
        if ([lay.presentationLayer hitTest:touchPoint]) {
            NSString *money = [self.dateSelfDic objectForKey:@"money"];
            [self qiangRedData];
            [[RedShowView shared] showTitle:money];
            [RedShowView shared].redButtonBlock = ^(UIButton *button) {
                [self loadData];
                [self endAction];
                MYHBViewController *myhb = [[MYHBViewController alloc] init];
                [[self getCurrentVC].navigationController pushViewController:myhb animated:YES];
            };
            [RedShowView shared].redCancelButtonBlock = ^(UIButton *button) {
                [self endAction];
            };
            break;
        }
    }
}

- (void)qiangRedData{
    NSString *str = [NSString stringWithFormat:@"%@890d69e502d1d37a9e84335ccefece57",[user objectForKey:@"token2"]];
    NSString *token = [LCMD5Tool md5:str];
    NSString *money = [self.dateSelfDic objectForKey:@"money"];
    NSArray *timeArray = [self.dateSelfDic objectForKey:@"time"];
    NSDictionary *selStringDic = [timeArray objectAtIndex:self.selTimeIndex];
    NSString *selString = [selStringDic objectForKey:@"time"];
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setValue:token forKey:@"verifyToken"];
    [parmas setValue:[user objectForKey:@"userid"] forKey:@"id"];
    [parmas setValue:money forKey:@"amountofmoney"];
    [parmas setValue:selString forKey:@"time"];
    
    NSString *url = [NSString stringWithFormat:@"%@/App/Voucher/getRed",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSInteger error = [[responseObject objectForKey:@"error"] integerValue];
        if (error == 200) {
            [self loadData];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}

- (void)start{
    [self.hbTimer invalidate];
    self.hbTimer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(showRain) userInfo:nil repeats:YES];
}

- (void)showRain{
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 40, 36)];
//    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    [imageView setImage:[UIImage imageNamed:@"rain_picture"]];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    
    self.moveLayer = [[CALayer alloc]init];
    [self.moveLayer setBounds:imageView.frame];
    self.moveLayer.anchorPoint = CGPointMake(0, 0);
    self.moveLayer.position = CGPointMake(0, -140);
    self.moveLayer.contents = (__bridge id _Nullable)(imageView.image.CGImage);
    [self.hbBgView.layer addSublayer:self.moveLayer];
    [self addAnimation];
}


- (void)addAnimation{
    CAKeyframeAnimation *moveAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    moveAnimation.values = [[NSArray alloc]initWithObjects:[NSValue valueWithCGPoint:CGPointMake(arc4random_uniform(ScreenWidth), 0)],[NSValue valueWithCGPoint:CGPointMake(arc4random_uniform(ScreenWidth), ScreenHeight)], nil];
    moveAnimation.duration = 2;
    moveAnimation.repeatCount = 1;
    moveAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    [self.moveLayer addAnimation:moveAnimation forKey:@"move"];
}

- (void)endAction{
    [self.hbTimer invalidate];
    NSArray *sublayers = self.hbBgView.layer.sublayers;
    for (int i = 0; i < sublayers.count; i ++) {
        CALayer *item = [sublayers objectAtIndex:i];
        [item removeAllAnimations];
        [item removeFromSuperlayer];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.hArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"Cell";
    
    HoongBaoItemTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"HoongBaoItemTableViewCell" owner:nil options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *itemDic = [self.hArray objectAtIndex:indexPath.row];
    NSString *phone = [itemDic objectForKey:@"phone"];
    NSString *amountofmoney = [itemDic objectForKey:@"amountofmoney"];
    NSString *currentcity = [itemDic objectForKey:@"currentcity"];
    if (phone.length == 11) {
        phone = [phone stringByReplacingCharactersInRange:NSMakeRange(3, 5)  withString:@"*****"];
    }
    if (currentcity.length > 4) {
        currentcity = [currentcity stringByReplacingCharactersInRange:NSMakeRange(4, currentcity.length - 4)  withString:@"*****"];
    }
    
    [cell.lbldiqu setText:currentcity];
    [cell.lblPhone setText:phone];
    [cell setContentLabelAtt:amountofmoney];
    return cell;
}

- (NSMutableArray *)hArray{
    if (!_hArray) {
        _hArray = [[NSMutableArray alloc]init];
    }
    return _hArray;
}

- (UIViewController *)getCurrentVC {
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    //app默认windowLevel是UIWindowLevelNormal，如果不是，找到UIWindowLevelNormal的
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    id nextResponder = nil;
    UIViewController *appRootVC=window.rootViewController;
    // 如果是present上来的appRootVC.presentedViewController 不为nil
    if (appRootVC.presentedViewController) {
        nextResponder = appRootVC.presentedViewController;
    }else{
        NSLog(@"===%@",[window subviews]);
        UIView *frontView = [[window subviews] objectAtIndex:0];
        nextResponder = [frontView nextResponder];
    }
    if ([nextResponder isKindOfClass:[UITabBarController class]]){
        UITabBarController * tabbar = (UITabBarController *)nextResponder;
        UINavigationController * nav = (UINavigationController *)tabbar.viewControllers[tabbar.selectedIndex];
        // UINavigationController * nav = tabbar.selectedViewController ; 上下两种写法都行
        result=nav.childViewControllers.lastObject;
    }else if ([nextResponder isKindOfClass:[UINavigationController class]]){
        UIViewController * nav = (UIViewController *)nextResponder;
        result = nav.childViewControllers.lastObject;
    }else{
        result = nextResponder;
    }
    return result;
}

- (void)dealloc{
    [self.hbTimer invalidate];
}

@end
